package com.aiju.cash.ui.billing;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiju.app.DataProviderManager;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Good;
import com.aiju.cash.R;
import com.aiju.cash.ui.billing.fragment.PaymentFragment;
import com.aiju.cash.ui.billing.fragment.SUNMIFragment;
import com.aiju.cash.ui.good.fragment.GoodFragment;
import com.aiju.cash.ui.good.manager.GoodManager;
import com.aiju.cash.ui.good.manager.ShopCart;
import com.aiju.cash.ui.pay.manager.PrintManager;
import com.aiju.cash.util.PrivateUtil;
import com.aiju.common.CommonFgtAdapter;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.DotView;
import com.aiju.widgit.dialog.EditWeighDialog;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.decoding.CaptureActivityHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @author: 佐为
 * @date: 2016-12-13 10:31
 * @version: V1.0
 * @Description: 开单
 */
public class BillingActivity extends BaseTitleActivity {

    private TextView goodTipNum, goodPrice;
    private DotView mDotView;
    private ViewPager mViewPager;
    private List<Fragment> mFragments;
    private Fragment currentFragment;

    private GoodManager goodManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_billing);
        setCenterTitle("开单");
        ImageView right = new ImageView(this);
        right.setImageResource(R.mipmap.icon_search_white);
        mAiJuTitleBarView.setCustomizedRightView(right);
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(SearchActivity.class);
            }
        });

        goodTipNum = (TextView) findViewById(R.id.tv_biling_tip);
        goodPrice = (TextView) findViewById(R.id.tv_shop_money);
        mDotView = (DotView) findViewById(R.id.indicatorBar);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);

        mFragments = new ArrayList<>();
        List<String> titles = new ArrayList();
        titles.add("手动选择");
        titles.add("扫码选择");
        titles.add("现金直输");
        mDotView.setTitles(titles);

        mFragments.add(getGoodFragment());
        if (DataProviderManager.getDataProvider().getModel().equals("V1")) {
            mFragments.add(new SUNMIFragment());
        } else {
            mFragments.add(getCaptureFragment());
        }
        mFragments.add(getPaymentFragment());
        currentFragment = mFragments.get(0);

        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(new CommonFgtAdapter(getSupportFragmentManager(), mFragments));
        mDotView.setViewPager(mViewPager);
        mDotView.setPageChange(new DotView.onPageChange() {
            @Override
            public void onPageChange(int position) {
                currentFragment = mFragments.get(position);
            }
        });

        TextView textView = (TextView) findViewById(R.id.tv_print_state);
        PrintManager.getInstance().setTextView(textView);
    }

    /**
     * 底部数据
     */
    private void setBottonView() {
        goodPrice.setText(goodManager.getTotalPrice());
        if (goodManager.getTotalSum().equals("0")) {
            goodTipNum.setVisibility(View.GONE);
        } else {
            goodTipNum.setVisibility(View.VISIBLE);
        }
        goodTipNum.setText(goodManager.getTotalSum());
    }

    /**
     * 二维码
     *
     * @return
     */
    private CaptureFragment getCaptureFragment() {
        CaptureFragment captureFragment = new CaptureFragment();
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera_billing);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        return captureFragment;
    }

    /**
     * 商品首页
     *
     * @return
     */
    private GoodFragment getGoodFragment() {
        Bundle bundle = new Bundle();
        bundle.putInt("show", GoodFragment.SHOP);
        final GoodFragment goodFragment = new GoodFragment();
        goodFragment.setOnData(new GoodFragment.OnData() {
            @Override
            public void onData() {
                goodManager = GoodManager.getInstance(BillingActivity.this);
                goodManager.addOnChangeListener(new GoodManager.OnChangeListener() {
                    @Override
                    public void changeView() {
                        setBottonView();
                    }
                });
                setBottonView();
                findViewById(R.id.rl_billing_shop).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (goodManager.getSelectedGoods().size() == 0) {
                            T.ToastShort("购物车为空");
                            return;
                        }
                        goodManager.setShopCartDialog(new ShopCart(BillingActivity.this));
                        goodManager.getShopCartDialog().setSystemAlert().show();
                    }
                });
                findViewById(R.id.tv_billing_order).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (goodManager.getSelectedGoods().size() == 0) {
                            T.ToastShort("购物车为空");
                            return;
                        }
                        startActivity(OrderActivity.class);
                    }
                });
            }
        });
        goodFragment.setArguments(bundle);
        return goodFragment;
    }

    /**
     * 现金直输
     *
     * @return
     */
    private PaymentFragment getPaymentFragment() {
        PaymentFragment paymentFragment = new PaymentFragment();
        return paymentFragment;
    }

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && data != null) {
            Bundle bundle = data.getExtras();
            ArrayList<HashMap<String, String>> result = (ArrayList<HashMap<String, String>>) bundle.getSerializable("data");
            Iterator<HashMap<String, String>> it = result.iterator();
            while (it.hasNext()) {
                HashMap<String, String> hashMap = it.next();
                //Log.i("sunmi", hashMap.get("TYPE"));//这个是扫码的类型
                //Log.i("sunmi", hashMap.get("VALUE"));//这个是扫码的结果
                //T.ToastShort(hashMap.get("VALUE"));
                codeSearchGood(hashMap.get("VALUE"));
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 根据二维码搜索商品
     *
     * @param code 二维码
     */
    private void codeSearchGood(String code) {
        //查询本地数据库，根据二维码获得商品，添加到购物车。
        List<Good> codeGood = goodManager.getGoodService().getCodeGood(code);
        if (Util.isEmpty(codeGood)) {
            T.ToastShort("未能找到该商品");
        } else {
            for (final Good good : codeGood) {
                if (good.isWeighGood()) {
                    final Good good1 = goodManager.getSelectedGoods().get(good.getIntId());
                    EditWeighDialog dialog = new EditWeighDialog(BillingActivity.this)
                            .setTitileText(good.getName())
                            .setMsgText(good.getPrice() + "/" + good.getUnit())
                            .setLayoutParams()
                            .setOnEditClick(new EditWeighDialog.OnEditClick() {
                                @Override
                                public void onCancel() {}
                                @Override
                                public void onSubmit(String msg) {
                                    if (TextUtils.isEmpty(msg)) {
                                        T.ToastShort("请输入商品重量");
                                        return;
                                    }
                                    if (good1 == null) {
                                        good.setWeigh(Double.valueOf(msg));
                                        goodManager.add(good, true);
                                    } else {
                                        good1.setWeigh(Double.valueOf(msg));
                                        goodManager.update(true);
                                    }
                                }
                            });
                    if (good1 != null) {
                        dialog.setContentText(String.valueOf(goodManager.getSelectedItemWeighById(good.getIntId())));
                    }
                    dialog.setCanceledOnTouchOutside(false).show();
                } else {
                    goodManager.add(good, true);
                }
            }
        }
    }

    /**
     * 二维码解析回调函数
     */
    private final CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {

        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            if (currentFragment instanceof CaptureFragment) {
                codeSearchGood(result);
                final CaptureActivityHandler handler = (CaptureActivityHandler) ((CaptureFragment) currentFragment).getHandler();
                if (handler != null) {
                    goodTipNum.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            PrivateUtil.invoke(handler, "restartPreviewAndDecode");
                        }
                    }, 3000);
                }
            }
        }

        @Override
        public void onAnalyzeFailed() {
            T.ToastShort("扫描失败，请重试");
        }
    };

}
